#!/bin/bash

# Function to get the battery percentage
getBattery() {
    BATT=$(cat /sys/class/power_supply/*{BAT,bat}*/uevent 2>/dev/null | grep -E "^POWER_SUPPLY_CAPACITY=" | sed -e 's/^POWER_SUPPLY_CAPACITY=//' | sort -rn | head -1)
    if ! test -n "${BATT}"; then
        NOW=$(cat /sys/class/power_supply/*{FUEL,fuel}*/uevent 2>/dev/null | grep -E "^POWER_SUPPLY_CHARGE_NOW=" | sed -e 's/^POWER_SUPPLY_CHARGE_NOW=//' | sort -rn | head -1)
        MAX=$(cat /sys/class/power_supply/*{FUEL,fuel}*/uevent 2>/dev/null | grep -E "^POWER_SUPPLY_CHARGE_FULL=" | sed -e 's/^POWER_SUPPLY_CHARGE_FULL=//' | sort -rn | head -1)
        if [ ! -z "$NOW" ] && [ ! -z "$MAX" ] && [ "$MAX" != 0 ]; then
            BATT=$((200 * $NOW / $MAX % 2 + 100 * $NOW / $MAX))
        fi
    fi
    echo ${BATT}
}

# Function to check if the ayn power supply is connected
is_power_connected() {
    PLUGGED=$(cat /sys/class/power_supply/*/online 2>/dev/null | grep -E "^1")
    if [ -n "${PLUGGED}" ]; then
        echo 1  # Power supply is connected
    else
        echo 0  # Power supply is not connected
    fi
}

# Initial power state
POWER_CONNECTED=$(is_power_connected)
if [[ "$POWER_CONNECTED" == 0 ]]; then
    /usr/bin/batocera-power-mode battery
fi

LAST_BATTERY=100
while true; do
    NEW_BATTERY=$(getBattery)
    DELAY=4
    CURRENT_POWER_CONNECTED=$(is_power_connected)

    # Check if power state has changed
    if [[ "$CURRENT_POWER_CONNECTED" != "$POWER_CONNECTED" ]]; then
        if [[ "$CURRENT_POWER_CONNECTED" == 0 ]]; then
            /usr/bin/batocera-power-mode battery
        else
            /usr/bin/batocera-power-mode ac
        fi
        POWER_CONNECTED="$CURRENT_POWER_CONNECTED"
    fi

    if [[ "$CURRENT_POWER_CONNECTED" == 0 ]]; then
        # Power not connected
        if test -z "${NEW_BATTERY}"; then
            exit 0
        fi
        if test "${NEW_BATTERY}" != "${LAST_BATTERY}"; then
            if test "${NEW_BATTERY}" -le 30; then
                if test "${NEW_BATTERY}" -lt "${LAST_BATTERY}"; then
                    if test "${NEW_BATTERY}" -le 10 -o $((${NEW_BATTERY} / 10)) -lt $((${LAST_BATTERY} / 10)); then
                        if test "${NEW_BATTERY}" -le 5; then
                            DELAY=10
                        fi
			LANG=en_US HOME=/userdata/system XAUTHORITY=/var/lib/.Xauthority DISPLAY=$(getLocalXDisplay) /usr/bin/batocera-flash-screen ${DELAY} red "$(/usr/bin/batocera-info --short)"
                    fi
                fi
            fi
        fi
    fi

    LAST_BATTERY=${NEW_BATTERY}
    sleep 5 # do a check every 5 seconds
done
